package com.itheima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.es.domain.Goods;
import com.itheima.common.es.feign.EsBookFeign;
import com.itheima.common.exception.BusinessException;
import com.itheima.common.response.ResponseResult;
import com.itheima.common.token.JwtUtil;
import com.itheima.user.domain.User;
import com.itheima.user.mapper.UserMapper;
import com.itheima.user.ro.LoginRO;
import com.itheima.user.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author liqp
 * @version 1.0
 * @date 2021/1/28
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EsBookFeign esBookFeign;


    public String login(LoginRO loginRO) {
        //登陆认证
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, loginRO.getUserName()).eq(User::getPassword, loginRO.getPassword());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException("用户名或者密码错误");
        }
        //校验通过生成token
        return JwtUtil.createJWT(UUID.randomUUID().toString(), loginRO.getUserName(), null);
    }

    public void delete(Integer id) {
        userMapper.deleteById(id);
    }

    public UserVO get(Integer id) throws Exception {
        User user = userMapper.selectById(id);
        UserVO userVO = new UserVO();
        userVO.setCreateTime(user.getCreateTime());
        userVO.setUpdateTime(user.getUpdateTime());
        userVO.setUserName(user.getUserName());
        userVO.setEmail(user.getEmail());
        return userVO;
    }


    public ResponseResult<List<Goods>> serchGoods() throws IOException {
        return esBookFeign.search(0, 100);
    }




}
